package com.rams.jhms.gui.components;

import java.awt.Component;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

public class FileSelector {
    private static String lastOpenedDir = null;

    public static File selectFolder(Component parent, String initialPath) {

        File f = new File(initialPath);
        if(!(f.exists() && f.isDirectory())) {
            initialPath = lastOpenedDir != null ? lastOpenedDir : "";
        }

        JFileChooser fileChooser = new JFileChooser(initialPath);
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fileChooser.addChoosableFileFilter(new FolderFilter());
        fileChooser.setAcceptAllFileFilterUsed(false);

        int code = fileChooser.showOpenDialog(parent);
        if(code == JFileChooser.APPROVE_OPTION) {
            File parentDir = fileChooser.getSelectedFile().getParentFile();
            if(parentDir != null)
               lastOpenedDir = parentDir.getAbsolutePath();
            
            return fileChooser.getSelectedFile();
        }

        return null;
    }


    private static class FolderFilter extends FileFilter {

        @Override
        public boolean accept(File f) {
            return f.isDirectory();
        }

        @Override
        public String getDescription() {
            return "Directories";
        }
    }

    public static File selectFile(Component parent, FileFilter filters[], boolean useAllFilter, boolean openMode) {

        JFileChooser fileChooser = lastOpenedDir != null ? new JFileChooser(lastOpenedDir) : new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        for (FileFilter filter : filters) {
            fileChooser.addChoosableFileFilter(filter);
        }

        int code = openMode ? fileChooser.showOpenDialog(parent) : fileChooser.showSaveDialog(parent);
        if(code == JFileChooser.APPROVE_OPTION) {
            File parentDir = fileChooser.getSelectedFile().getParentFile();
            if(parentDir != null)
               lastOpenedDir = parentDir.getAbsolutePath();

            return fileChooser.getSelectedFile();
        }

        return null;
    }
}
